package com.jas.common;
//@author A0098803W
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import com.jas.storage.StorageAPI;
import com.jas.storage.StorageException;

//@author A0098803W
/**
 * This class handles the default storage for the message gateway.
 * 
 */
public class MessageGateway {
	private final String USER_AGENT = "Mozilla/5.0";
	private String gatewayUrl;

	//@author A0098803W
	/**
	 * Gets the default message gateway URL.
	 * 
	 * @return Returns the default message gateway URL.
	 * @throws StorageException
	 */
	public String getGatewayUrl() throws StorageException {
		this.gatewayUrl = StorageAPI.getGatewaySettings();
		return gatewayUrl;
	}

	//@author A0098803W
	/**
	 * Sets the default message gateway URL.
	 * 
	 * @param gatewayUrl
	 *            The message gateway URL to use for all notification.
	 * @throws StorageException
	 */
	public void setGatewayUrl(String gatewayUrl) throws StorageException {
		this.gatewayUrl = gatewayUrl;
		StorageAPI.storeGatewaySettings(this.gatewayUrl);
	}

	public boolean sendMessage(Notification notify) {

		try {
			String url = StorageAPI.getGatewaySettings() + notify.getMessage();

			URL obj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();

			// optional default is GET
			con.setRequestMethod("GET");

			// add request header
			con.setRequestProperty("User-Agent", USER_AGENT);

			int responseCode = con.getResponseCode();
			

			BufferedReader in = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			
		} catch (IOException | StorageException e) {
			return false;
		}

		return true;

	}

}
